<template>
  <el-dialog
    :visible="visible"
    :title="title"
    class="add-basemap-dialog"
    align-center
    @opened="handleDialogOpen"
    @close="closeDialog"
    width="662px"
  >
    <el-form
      :model="baseMapForm"
      :rules="baseMapRules"
      ref="baseMapFormRef"
      label-width="100px"
    >
      <el-form-item label="底图名称" prop="mapName">
        <el-input v-model="baseMapForm.mapName" />
      </el-form-item>
      <el-form-item label="服务类型" prop="serviceType">
        <el-select
          v-model="baseMapForm.serviceType"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="(item, index) in baseMapServerDict"
            :key="index"
            :label="item.label"
            :value="item.value"
            :disabled="item.value === 'socialmanager'"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务地址" prop="mapUrl">
        <el-input v-model="baseMapForm.mapUrl" />
      </el-form-item>
      <!--      <el-form-item label="地形地址" prop="remark">-->
      <!--        <el-input-->
      <!--          v-model="baseMapForm.remark"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="是否默认">
        <el-radio-group v-model="baseMapForm.isDefault">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="缩略图">
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :auto-upload="false"
          accept="image/png, image/jpeg,image/jpg, image/gif, .svg"
          :on-change="handleFileChange"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <!--          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>-->
          <i class="avatar-uploader-icon el-icon el-icon-plus" v-else></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit"> 确定 </el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { Message as ElMessage } from 'element-ui'
// import { Plus } from '@element-plus/icons-vue'
import {
  addBaseMap,
  updateBaseMap,
  uploadMapFile,
} from '@/api/back-management/basemap'
import type { PropType } from 'vue'
import type { addBaseMapParams } from '@/api/back-management/basemap/interface'
import type { BaseMapDataResp } from '@/api/back-management/basemap'
import type { OptionData } from '@/utils/type'
import { baseFileUrl } from '@/utils'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  basemapInfo: {
    type: Object as PropType<Partial<BaseMapDataResp>>,
    default: () => {},
  },
  baseMapServerDict: {
    type: Array as PropType<OptionData[]>,
    default: () => [],
  },
})

const title = ref('新增底图')

const imageUrl = ref('')

const emit = defineEmits(['closeDialog', 'updateBaseMap'])

const closeDialog = () => {
  baseMapFormRef.value?.clearValidate()
  emit('closeDialog')
}

const baseMapForm = reactive<addBaseMapParams>({
  mapName: '',
  mapUrl: '',
  fileId: '',
  isDefault: 1,
  serviceType: '',
  pkid: '',
})

const baseMapFormRef = ref()

const baseMapRules = reactive({
  mapName: [
    {
      required: true,
      message: '底图名称不能为空',
      trigger: 'blur',
    },
  ],
  mapUrl: [
    {
      required: true,
      message: '服务地址不能为空',
      trigger: 'blur',
    },
  ],
  serviceType: [
    {
      required: true,
      message: '请选择服务类型',
      trigger: 'change',
    },
  ],
})

const isImage = (filename: string) => {
  const ext = filename.split('.').pop()!.toLowerCase() // Get the file extension in lowercase
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'svg'] // List of image extensions
  return imageExtensions.indexOf(ext) !== -1 // Check if the extension is in the list of image extensions
}

const beforeAvatarUpload = (rawFile) => {
  if (!isImage(rawFile.name)) {
    ElMessage.error('上传的文件必须是图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('上传的文件大小不能大于1M')
    return false
  }
  return true
}

const handleFileChange = (file) => {
  // console.log(file);
  const form = new FormData()
  if (file.raw) {
    form.append('file', file.raw)
    uploadMapFile(form).then((res) => {
      if (res.success) {
        baseMapForm.fileId = res.data
        imageUrl.value = URL.createObjectURL(file.raw!)
        ElMessage.success('上传文件成功！')
      } else {
        ElMessage.error(res.message)
      }
    })
  }
}

const onSubmit = () => {
  baseMapFormRef.value?.validate((valid) => {
    if (valid) {
      const params = { ...baseMapForm }
      if (baseMapForm.pkid) {
        updateBaseMap(baseMapForm.pkid, params).then((res) => {
          if (res.success) {
            emit('updateBaseMap')
            ElMessage.success('更新底图成功！')
          } else {
            ElMessage.error(res.message)
          }
        })
      } else {
        addBaseMap(params).then((res) => {
          if (res.success) {
            emit('updateBaseMap')
            ElMessage.success('新增底图成功！')
          } else {
            ElMessage.error(res.message)
          }
        })
      }
    }
  })
}

const getImageUrl = (url: string) => {
  if (url) {
    return baseFileUrl + url
  } else {
    return ''
  }
}

const handleDialogOpen = () => {
  if (props.basemapInfo) {
    baseMapFormRef.value?.resetFields()
    const { pkid, mapName, mapUrl, fileId, fileUrl, isDefault, serviceType } =
      props.basemapInfo
    baseMapForm.pkid = pkid
    baseMapForm.mapName = mapName!
    baseMapForm.mapUrl = mapUrl
    baseMapForm.fileId = fileId
    baseMapForm.isDefault = isDefault
    baseMapForm.serviceType = serviceType
    if (fileUrl) {
      imageUrl.value = getImageUrl(fileUrl)
    } else {
      imageUrl.value = ''
    }
    if (pkid) {
      title.value = '编辑底图'
    } else {
      title.value = '新增底图'
    }
  }
}
</script>

<style lang="scss">
.add-basemap-dialog {
  //width: 762px;
  //height: 643px;
  //background: #ffffff;
  border-radius: 4px;
  .el-dialog__body {
    padding-bottom: 0 !important;
  }
  .el-dialog__footer {
    padding-top: 30px !important;
    border-top: 1px solid #e5e5e5;
  }

  .el-dialog__header {
    border-bottom: 1px solid #e5e5e5;

    .el-dialog__title {
      width: 64px;
      height: 16px;
      font-size: 16px;
      font-weight: bold;
      color: #27475f;
    }
  }

  .el-form {
    .el-form-item {
      min-height: 42px;
      margin-bottom: 21px;
      align-items: center;

      //&:last-child {
      //  margin-bottom: 0;
      //}
    }

    .el-cascader {
      width: 100%;
    }

    .el-select {
      width: 100%;
    }
  }

  .dialog-footer {
    width: 100%;
    height: 100%;
    text-align: center;
  }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader {
  display: flex;

  .el-upload {
    display: flex;
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    &:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
</style>
